import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import AIRecommendationsView from '../views/AIRecommendationsView.vue'
import { isLoggedIn } from '../services/auth'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
      meta: { title: '首页 - 视频小站' }
    },
    {
      path: '/video/:id',
      name: 'videoDetail',
      component: () => import('../views/VideoDetailView.vue'),
      meta: { title: '视频详情 - 视频小站' }
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/LoginView.vue'),
      meta: { title: '登录 - 视频小站' }
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('../views/RegisterView.vue'),
      meta: { title: '注册 - 视频小站' }
    },
    {
      path: '/user/profile',
      name: 'userProfile',
      component: () => import('../views/UserProfileView.vue'),
      meta: { title: '个人中心 - 视频小站', requiresAuth: true }
    },
    {
      path: '/category/:name',
      name: 'category',
      component: () => import('../views/CategoryView.vue'),
      meta: { title: '分类浏览 - 视频小站' }
    },
    {
      path: '/search',
      name: 'search',
      component: () => import('../views/SearchView.vue'),
      meta: { title: '搜索结果 - 视频小站' }
    },
    {
      path: '/ai-recommendations',
      name: 'ai-recommendations',
      component: AIRecommendationsView,
      meta: { title: 'AI智能电影推荐 - 视频小站' }
    },
    {
      path: '/membership',
      name: 'membership',
      component: () => import('../views/MembershipView.vue'),
      meta: { title: '会员中心 - 视频小站', requiresAuth: true }
    },
    {
      path: '/user/history',
      name: 'viewingHistory',
      component: () => import('../views/ViewingHistoryView.vue'),
      meta: { title: '观看历史 - 视频小站', requiresAuth: true }
    },
    {
      path: '/customer-service',
      name: 'customerService',
      component: () => import('../views/CustomerServiceView.vue'),
      meta: { title: '客服与投诉 - 视频小站' }
    },
    // 捕获所有未匹配的路由，重定向到首页
    // 视频上传页面（需要登录）
    {
      path: '/upload-video',
      name: 'uploadVideo',
      component: () => import('../views/UploadVideoView.vue'),
      meta: { title: '上传视频 - 视频小站', requiresAuth: true }
    },
    // 捕获所有未匹配的路由，重定向到首页
    { path: '/:pathMatch(.*)*', redirect: '/' }
  ],
  // 页面滚动行为
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

// 路由守卫：检查登录状态
router.beforeEach((to, from, next) => {
  // 动态设置页面标题
  document.title = to.meta.title || '视频小站';
  
  // 检查是否需要登录
  if (to.meta.requiresAuth && !isLoggedIn()) {
    // 未登录，跳转到登录页
    next({ name: 'login', query: { redirect: to.fullPath } });
  } else {
    // 已登录或不需要登录，直接通过
    next();
  }
})

export default router
